
#include "miner.h"
#include "towerinfo.h"
#include "gameplayscene.h"
#include "gamemanager.h"
#include "gamedatamanager.h"
#include "CCSkeletalSprite.h"
#include "mine.h"
#include "gameplayscene.h"
#include "camp.h"

#define __super			Soldier

Miner::Miner() :
	_workTime(0.0f)
	, mine(nullptr)
{

}

Miner::~Miner() {

}

void Miner::handleStateWalk( float ticks )
{
	if(!move(ticks)) {
		switch(state) {
		case UnitState::walk_to_flag:
			walkToMine();
			break;
		case UnitState::walk_to_mining:
			transformState(UnitState::work);
			break;
		case UnitState::back_to_camp:
			GDM->money += 10;

			if(!mine) {
				regroup();
			} else {
				walkToMine();
			}
			break;
		default:break;
		}
	}
}

void Miner::walkToMine()
{
	if(!mine) {
		mine = findMine();
	}

	if(mine){
		targetPosition = mine->position;
		if(position.x < mine->position.x) {
			targetPosition.x -= 50.0f;
		} else {
			targetPosition.x += 50.0f;
		}

		float angle = (targetPosition - position).getAngle();
		speed = (Point(attribute.speed, 0)).rotateByAngle(Point::ZERO, angle);

		sprite->setFlipX(targetPosition.x < position.x);

		transformState(UnitState::walk_to_mining);
	}
}

Mine* Miner::findMine()
{
	Mine* ret = nullptr;
	float minDistance = 9999.0f;

	for(Mine* item: gamePlayScene->mines) {
		float distance = position.getDistance(item->position);
		if(distance < minDistance) {
			ret = item;
			minDistance = distance;
		}
	}

	return ret;
}

void Miner::handleStateWork( float ticks )
{
	_workTime  += ticks;

	if(_workTime >= attribute.duration) {
		_workTime = 0.0f;

		backToCamp();
	}
}

void Miner::regroup()
{
	__super::regroup();

	mine = nullptr;
}

void Miner::backToCamp()
{
	targetPosition = gamePlayScene->camp->position;

	float angle = (targetPosition - position).getAngle();
	speed = (Point(attribute.speed, 0)).rotateByAngle(Point::ZERO, angle);

	sprite->setFlipX(targetPosition.x < position.x);

	transformState(UnitState::back_to_camp);
}

